package com.zing.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zing.constant.MessageConstant;
import com.zing.constant.OtherConstant;
import com.zing.dto.UserLoginDTO;
import com.zing.entity.User;
import com.zing.exception.LoginFailedException;
import com.zing.mapper.UserMapper;
import com.zing.properties.WeChatProperties;
import com.zing.service.UserService;
import com.zing.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    // 用户登录
    public User login(UserLoginDTO userLoginDTO) {
        //获取openid
        String openid = getOpenid(userLoginDTO);

        // 判断openid是否为空, 如果为空, 标识登录失败, 抛出业务异常
        if(openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断当前用户是否为新用户 查询当前用户信息, 如果没有则是新用户
        User user = userMapper.getByOpenid(openid);

        // 如果是新用户, 自动完成注册
        if(user == null) {
            user = new User();
            BeanUtils.copyProperties(userLoginDTO, user);
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        // 返回用户对象
        return user;
    }

    //调用微信接口服务, 获得当前微信用户的openid
    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String jsonString = HttpClientUtil.doGet(OtherConstant.GET_OPENID_URL, paramMap);
        log.info("微信服务返回结果: {}", jsonString);

        JSONObject jsonObject = JSON.parseObject(jsonString);
        return jsonObject.getString("openid");
    }
}
